package GoodsService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/request/GoodsReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/response/GoodsResp"
	"gdshop-back-end-go/common/tools"
	"gdshop-back-end-go/service-order/FenxiaoService"
	"gdshop-back-end-go/service-other/GoodsActivityService"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"time"
)

func Details(ctx context.Context, parames *GoodsReq.Details) *response.JsonResponse {
	goodsModel, err := GetGoodsModel(ctx, parames.Id)
	if err != nil {
		return tools.GetErrNoRowsResponse(err, "成功，无数据", true)
	}

	// 取出规格
	goodsModel.Specs = getGoodsSpecs(ctx, parames.Id)
	// 商品是否收藏，用户未登陆或者没收藏都是返回false
	goodsModel.IsCollection = goodsIsCollection(ctx, parames.Id, int(parames.MemberId))
	resultMap := gconv.Map(goodsModel)
	// 获取活动
	tags, err := GoodsActivityService.GetGoodsActivityTagByGoodsId(ctx, parames.Id)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	resultMap["tags"] = tags
	// 获取商品属性信息
	resultMap["attributes"] = getGoodsAttribute(ctx, parames.Id)
	resultMap["photo_base_url"] = g.Cfg().GetString("site.PhotoUrlProfix")
	// 获取分销信息
	resultMap["fenxiao_info"] = getGoodsFenxiaoInfo(ctx, int(parames.MemberId), parames.Id)
	// 获取团购列表
	if goodsModel.TuanInfo.TuanId > 0 {
		resultMap["tuan_list"] = getGoodsTuanList(ctx, parames.Id, parames.MemberId)
	}
	// 删除多余的数据
	delete(resultMap, "create_at")
	delete(resultMap, "update_at")
	delete(resultMap, "display_sort")
	return response.SuccessByRequestMessageData(nil, "成功", resultMap)
}

func goodsIsCollection(ctx context.Context, goodsId int, memberId int) bool {
	if memberId < 1 || goodsId < 1 {
		return false
	}
	count, err := toolsDb.GetUnSafaTableAddDeleteWhere(
		ctx,
		"member_collection").Where(g.Map{
		"member_id": memberId,
		"goods_id":  goodsId,
	}).Fields("1").Count()
	if err != nil {
		return false
	}

	return count > 0
}

func getGoodsFenxiaoInfo(ctx context.Context, memberId, goodsId int) g.Map {
	fanhui := g.Map{}

	fanhui["fenxiao_text"] = "佣金"

	config, err := FenxiaoService.BaseGetConfig()
	if err != nil {
		fanhui["level_name"] = "一级"
	} else {
		if config.SelfPurchaseRebate == 1 {
			fanhui["level_name"] = "自购返"
		} else {
			fanhui["level_name"] = "一级"
		}
	}
	if memberId < 1 {
		fanhui["money"] = 0
	} else {
		fanhui["money"] = FenxiaoService.GetMemberGoodsDetailsBrokerage(ctx, memberId, goodsId)
	}

	return fanhui
}

func getOneTuanInfoByGoodsId(ctx context.Context, goodsId int) *GoodsResp.GoodsTuanInfo {
	dbPrefix := g.Cfg().GetString("database.prefix")
	one, err := toolsDb.GetUnSafaTable(ctx, "goods_activity").As("ga").Fields("ga.*").LeftJoin(
		dbPrefix+"goods_activity_goods_list as gagl", "gagl.activity_id = ga.id AND gagl.delete_at<1").Where(
		"ga.delete_at < 1 AND ga.activity_type = 6 AND start_time <= UNIX_TIMESTAMP(NOW()) AND end_time >= UNIX_TIMESTAMP(NOW()) AND gagl.goods_id = ?",
		goodsId).Where("ga.status = 1").OrderDesc("ga.sort").One()

	fanhui := &GoodsResp.GoodsTuanInfo{}
	fanhui.TuanId = 0
	if err != nil {
		return fanhui
	}

	fanhui.TuanId = gconv.Int(one["id"])
	fanhui.TuanName = gconv.String(one["activity_name"])
	fanhui.TuanEndTime = gconv.Int64(one["end_time"])
	if (fanhui.TuanId > 0) && (fanhui.TuanEndTime > time.Now().Unix()) {
		// 查询参团人数
		count, err := toolsDb.GetUnSafaTable(ctx, "order_tuan").Where(g.Map{
			"tuan_id":  fanhui.TuanId,
			"goods_id": goodsId,
		}).Count()
		if err != nil {
			return fanhui
		}
		fanhui.JoinNum = count
	}

	return fanhui
}

// 显示当前可以参加的团购
func getGoodsTuanList(ctx context.Context, goodsId int, memberId int) []*GoodsResp.GoodsTuanList {
	return getGoodsTuanListByWhere(ctx, memberId, g.Map{
		"ot.goods_id = ?":  goodsId,
		"o.status = ?":     2,
		"ot.tuan_type = ?": 1,
		"ot.status = ?":    1,
	}, 10)
}

func getGoodsTuanListByWhere(ctx context.Context, memberId int, where g.Map, limit int) []*GoodsResp.GoodsTuanList {
	//dbPrefix := g.Cfg().GetString("database.prefix")
	// order 状态在 2待备货 才能参团
	fields := "ot.*"
	fields += ",o.total_price"
	fields += ",m.nickname as member_name,m.avatar as member_avatar"
	all, err := toolsDb.GetUnSafaTable(ctx, "order_tuan").As("ot").Fields(fields).LeftJoin(
		"order o", "o.id = ot.order_id").LeftJoin(
		"goods_activity as ga", "ga.id = ot.tuan_id AND ga.delete_at<1").LeftJoin(
		"member as m", "m.id = ot.member_id AND m.delete_at<1").Where(
		"ga.activity_type = 6 AND start_time <= UNIX_TIMESTAMP(NOW()) AND end_time >= UNIX_TIMESTAMP(NOW()) AND ga.status = 1").
		Where(where).
		Where("ot.close_time > UNIX_TIMESTAMP(NOW())").OrderAsc("ot.close_time").Limit(limit).All()
	if err != nil {
		return nil
	}

	var fanhui []*GoodsResp.GoodsTuanList
	var tuanId int64 = 0
	var tuanJoinId string = ""
	for _, v := range all {
		tuanId = gconv.Int64(v["tuan_id"])
		tuanJoinId = gconv.String(v["tuan_join_id"])
		leaveNum, err := GetGoodsActivityRuleTuanLeaveNum(ctx, tuanId, tuanJoinId)
		if err != nil {
			return nil
		}
		if leaveNum < 1 {
			// 没有剩余的人数，跳过
			continue
		}
		tuanMaxNum, err := GetGoodsActivityRuleTuanMaxNum(ctx, tuanId)
		if err != nil {
			continue
		}
		item := &GoodsResp.GoodsTuanList{}
		item.TuanId = int(tuanId)
		item.TuanJoinId = tuanJoinId
		item.CloseTime = gconv.Int64(v["close_time"])
		item.TimeoutSeconds = item.CloseTime - time.Now().Unix()
		item.MemberId = gconv.Int(v["member_id"])
		item.MemberName = gconv.String(v["member_name"])
		item.MemberAvatar = gconv.String(v["member_avatar"])
		item.LeaveNum = int(leaveNum)
		item.JoinMaxNum = int(tuanMaxNum)
		item.IsJoin = 0
		item.TuanStatus = gconv.Int(v["status"])
		item.TuanStatusText = GetTuanStatusText(item.TuanStatus)
		item.TuanPrice = gconv.Int64(v["total_price"])
		if item.MemberId == memberId {
			item.IsJoin = 1
		}
		fanhui = append(fanhui, item)
	}
	return fanhui
}

// 获取商品参团人数，这个数量包含团长
func getGoodsTuanNum(ctx context.Context, tuanJoinId string, isPay bool) int {
	if isPay {
		// 只统计已支付的
		count, err := toolsDb.GetUnSafaTable(ctx, "order_tuan").As("ot").
			LeftJoin("order o", "o.id = ot.order_id").
			Where("ot.tuan_join_id = ? AND o.status = 2", tuanJoinId).Count()
		if err != nil {
			return 0
		}
		return count
	} else {
		// 统计所有参团人数
		count, err := toolsDb.GetUnSafaTable(ctx, "order_tuan").Where(g.Map{
			"tuan_join_id": tuanJoinId,
		}).Count()
		if err != nil {
			return 0
		}
		return count
	}
}
